# -*- coding: utf-8 -*-
__author__ = 'vladbranzei'

import sys, pymongo, os
from pymongo import MongoClient
from pymongo.errors import DuplicateKeyError

def create(host, port, username=None, password=None):
    client = MongoClient(host, int(port))
    db = client.freya
    if username:
        client.admin.authenticate(username, password)
    collection = db.players
    try:
        result = collection.insert({'init':'init'})
        if result:
            print('freya.players created')

            index_name = "vid"
            res = collection.ensure_index([("vid", pymongo.ASCENDING)], unique=True, name="vid")
            if index_name == res:
                print(index_name + " index created")

            index_name = "credentials_game"
            res = collection.ensure_index([("credentials", pymongo.ASCENDING),("game", pymongo.ASCENDING)], unique=True, name="credentials_game")
            if index_name == res:
                print(index_name + " index created")
            else:
                print("an error occurred while creating index " + index_name)
        else:
            print('an error occurred while creating players')
    except DuplicateKeyError:
        print("freya.players already exists")

    collection = db.permissions
    try:
        result = collection.insert({'init':'init'})
        if result:
            print('freya.permissions created')
            index_name = "vid"
            res = collection.ensure_index([("vid", pymongo.ASCENDING)], unique=True, name="vid")
            if index_name == res:
                print(index_name + " index created")
            else:
                print("an error occurred while creating index " + index_name)
        else:
            print('an error occurred while creating permissions')
    except DuplicateKeyError:
        print("freya.permissions already exists")

if __name__ == '__main__':
    if len(sys.argv) == 3:
        host = sys.argv[1].split('=')[1]
        port = sys.argv[2].split('=')[1]
        print('host = ' + host + ' port = ' + port)
        create(host, port)

    else:
        host = os.environ['OPENSHIFT_MONGODB_DB_HOST']
        port = os.environ['OPENSHIFT_MONGODB_DB_PORT']
        username = os.environ['OPENSHIFT_MONGODB_DB_USERNAME']
        password = os.environ['OPENSHIFT_MONGODB_DB_PASSWORD']
        print('host = ' + host + ' port = ' + port)
        create(host, port, username, password)

